<template>
  <div style="width: 100%;height: 100%;">
    <Toolbar
      id="toobar"
      style="width: 100%; padding: 0; border: 1px solid #ddd;"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"/>
    <Editor
    id="edtior"
    style="width: 100%;height: 300px;min-height:300px;max-height:55vh;overflow-y: auto; border: 1px solid #ddd;"
    v-model:modelValue="valueHtml"
    :defaultConfig="editorConfig"
    mode="simple"
    @onCreated="handleCreated"
    @onChange="handleChange"/>
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { ElMessage } from 'element-plus';
import { IDomEditor } from '@wangeditor/editor';

// 声明属性-当父组件传递数据发生变化时触发
const props = defineProps<{
  modelValue: string,
}>();
//! 声明事件消息-当valueHtml发生变化时触发
const emit = defineEmits<(e: "update:modelValue", value: String) => void>();

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref('');

watch(() => props.modelValue, (newValue) => {
  valueHtml.value = newValue;
}, { immediate: true });


// 父传入变更时同步本地值；本地变更只在 onChange 中向外触发

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
      valueHtml.value = props.modelValue;
    }, 300);
});


// 工具配置
const toolbarConfig = {toolbarKeys: ["uploadImage"]};
const editorConfig = {
  placeholder: '请输入内容...',
  scroll: true,
  autoFocus: false,
  // 上传图片配置
  MENU_CONF: {
    uploadImage: {
      server: "/saferycom/file/upload_file",
      fieldName: "file",
      allowedFileTypes: ["image/*"],
      uploadImgMaxSize: 10 * 1024 * 1024, // 设置图片最大上传大小为10MB
      maxFileSize: 10 * 1024 * 1024, // 设置文件大小限制为10MB
      headers: {
        token: localStorage.getItem("TOKEN"),
      },
      customInsert: async (result: any, insertFn: any) => {
        if (result.code === 200) {
            insertFn(result.data.resultFilePath); //上传到服务器
        } else {
          ElMessage.error("上传图片失败");
          throw new Error();
        }
      },
    },
  },
};


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (editor: IDomEditor) => {
  // 只向外抛出当前内容，避免在编辑中改写 HTML 导致 Slate 光标映射异常
  emit("update:modelValue", editor.getHtml());
};
</script>
